#include "player.h"
#include<QEventLoop>

Player::Player(QWidget *parent) : QWidget(parent)
{
    // 右键菜单
    m_contextMenu = new QMenu;
    m_playAction = new QAction("播放",this);

    m_videoCap = nullptr;
    m_timer = new QTimer;

    // 右键菜单处理事件
    connect(m_contextMenu,SIGNAL(triggered(QAction*)),this,SLOT(menu(QAction*)));
    connect(m_timer,SIGNAL(timeout()),this,SLOT(readFrame()));
}

void Player::setPlayer(QLabel *player)
{
    m_player = player;
}

void Player::menu(QAction *action)
{
    if(action == m_playAction){

    }
}

void process(Mat *img,Mat *dst)
{
    resize(*img,*dst,Size(128,64),INTER_CUBIC);


}

void Player::readFrame()
{
    m_videoCap->read(image);

    if(image.empty())return;

    process(&image,&image);

    QImage qImg = QImage((const unsigned char*)(image.data),
                         image.cols,image.rows,image.step,QImage::Format_RGB888);
    QPixmap qPix = QPixmap::fromImage(qImg);
    m_player->setPixmap(qPix);

}

void Player::start(int msec)
{
    m_timer->start(msec);
}

void Player::stop()
{
    m_timer->stop();
}


/**
 * @brief Player::close
 * 关闭播放器
 */
void Player::close()
{
    m_timer->stop();
    if(m_videoCap != nullptr)m_videoCap->release();
}

void Player::readFromCamera(int capNum)
{
    type = FileType_Camera;
    m_videoCap = new VideoCapture(capNum);
    start(33);
}

void Player::readFromLocalVideo(QString filePath,PlayMode mode)
{
    if(!filePath.size()){
        return;
    }
    // 中文路径编码
    std::string path = filePath.toLocal8Bit().toStdString();

    m_videoCap = new VideoCapture(path);
    type = FileType_LocalVideo;

    start(33);
}


void Player::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::RightButton){
        m_contextMenu->addAction(m_playAction);
        m_contextMenu->exec(QCursor::pos());
    }
}
